package com.qc31.monitorlib.custom

import android.content.Context
import android.content.res.TypedArray
import android.graphics.drawable.ColorDrawable
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.FrameLayout
import android.widget.PopupWindow
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.qc31.comlib.choose.car.ChooseCars
import com.qc31.comlib.net.ServiceHelper
import com.qc31.baselib.R
import com.qc31.baselib.rx.textChangesNoLong
import com.qc31.baselib.utils.sub
import com.qc31.baselib.utils.subPlate
import com.qc31.baselib.utils.toast
import com.qc31.comlib.entity.CarLick
import com.qc31.monitorlib.databinding.CustomEditBinding
import com.qc31.monitorlib.databinding.PopupSearchRecyclerBinding
import io.reactivex.rxjava3.disposables.Disposable


/** @Author Jasper @Time 2020/11/2 @Desc 自定义搜索车辆 */
class SearchCarEditText : FrameLayout {
    var isChoose = false
    private var textLength = 0

    constructor(context: Context) : super(context) {
        initView(context, null)
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        initView(context, attrs)
    }

    constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(
        context,
        attrs,
        defStyle
    ) {
        initView(context, attrs)
    }

    private lateinit var binding: CustomEditBinding

    //是否首次进入
    private var isFirst = true

    //是否赋值
    private var isSetText = false

    /** Is car login */
    var isShowChoose = false

    private fun initView(context: Context, attrs: AttributeSet?) {
        ChooseCars.initData()
        binding = CustomEditBinding.inflate(LayoutInflater.from(context), this, true)
        val typedArray: TypedArray =
            context.obtainStyledAttributes(attrs, R.styleable.custom_edit)
        val hint = typedArray.getString(R.styleable.custom_edit_custom_hint)
        binding.editCustomSearch.hint = hint
        binding.editCustomSearch.setTextColor(
            ContextCompat.getColor(
                context,
                R.color.color_F69
            )
        )
        binding.editCustomSearch.textChangesNoLong().subscribe {
            if (it.isNullOrEmpty() && !isSetText) {
                if (isFirst) {
                    isFirst = false
                    binding.editCustomSearch.postDelayed({
                        if (isShowChoose) return@postDelayed
                        bindingPopup.tvSearchLogo.isVisible = true
                        initPopup()
                        mAdapter.setList(ChooseCars.getLickCars())
                    }, 300)

                } else {
                    bindingPopup.tvSearchLogo.isVisible = true
                    isFirst = false
                    initPopup()
                    mAdapter.setList(ChooseCars.getLickCars())
                }
                return@subscribe
            }
            bindingPopup.tvSearchLogo.isVisible = false
            if (it.length < textLength) {
                isSetText = false
                binding.editCustomSearch.setTextColor(
                    ContextCompat.getColor(
                        context,
                        R.color.color_F69
                    )
                )
                isChoose = false
            }
            if (it.isNotEmpty()) {
                if (isShowDelete) {
                    binding.ivCustomDelete.visibility = View.VISIBLE
                }
                if (!isChoose) {
                    initPopup()
                    searchCar(it)
                }
            } else {
                isChoose = false
                binding.ivCustomDelete.visibility = View.INVISIBLE
                dismiss()
            }
        }
        binding.ivCustomDelete.setOnClickListener {
            isChoose = false
            isSetText = false
            dismiss()
            binding.editCustomSearch.setTextColor(
                ContextCompat.getColor(
                    context,
                    R.color.color_F69
                )
            )
            binding.editCustomSearch.setText("")
            it.visibility = View.INVISIBLE
        }
        typedArray.recycle()
    }

    private fun dismiss() {
        mListPop?.let {
            if (it.isShowing) it.dismiss()
        }
    }

    private var subscribe: Disposable? = null
    private fun searchCar(plate: String) {
        subscribe?.dispose()
        subscribe = ServiceHelper.getRepository().getSearchCar(plate, "1", false).subscribe({
            if (it.isNullOrEmpty()) {
                R.string.toast_query_no_car.toast(context)
                mAdapter.setList(it)
            } else {
                mAdapter.setList(it)
            }
        }, {
            R.string.toast_query_no_car.toast(context)
            dismiss()
        })
    }

    private var mListPop: PopupWindow? = null
    private val mAdapter by lazy { EditAdapter() }
    private val bindingPopup by lazy {
        PopupSearchRecyclerBinding.inflate(
            LayoutInflater.from(
                context
            )
        )
    }

    private fun initPopup() {
        mListPop?.run {
            if (!isShowing) showAsDropDown(binding.editCustomSearch)
            return
        }

        mListPop = PopupWindow().apply {
            width = binding.editCustomSearch.measuredWidth
            height = ViewGroup.LayoutParams.WRAP_CONTENT

            isOutsideTouchable = true

            inputMethodMode = PopupWindow.INPUT_METHOD_NEEDED;
            softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;

            setBackgroundDrawable(ColorDrawable(0xFFFFFFFF.toInt()))


            contentView = bindingPopup.root

            bindingPopup.recyclerView.layoutManager = LinearLayoutManager(context)
            bindingPopup.recyclerView.adapter = mAdapter.apply {
                setOnItemClickListener { adapter, view, position ->
                    val entity = adapter.data[position] as CarLick

                    setText(subPlate(entity.carPlate))
                    carIdBack?.back(entity)
                    mListPop?.dismiss()
                    //添加
                    ChooseCars.addCars(
                        carId = entity.carId,
                        carPlate = entity.carPlate,
                        carName = entity.carName,
                        videos = entity.videos,
                        iconLink = entity.iconLink,
                        isVideo = !entity.videos.isNullOrEmpty()
                    )
                }
            }
            showAsDropDown(binding.editCustomSearch)
        }
    }

    fun setText(title: String) {
        isSetText = true
        isChoose = true
        textLength = title.length
        binding.editCustomSearch.setTextColor(
            ContextCompat.getColor(
                context,
                R.color.color_28C
            )
        )
        binding.editCustomSearch.setText(subPlate(title, 14))
        binding.editCustomSearch.setSelection(binding.editCustomSearch.text.length)
    }

    //是否显示delete图标
    private var isShowDelete = true
    fun setEnable(isEnable: Boolean) {
        binding.editCustomSearch.isEnabled = isEnable
        isShowDelete = false
    }

    private var carIdBack: OnCarIdBack? = null
    fun setOnCarIdBack(carIdBack: OnCarIdBack) {
        this.carIdBack = carIdBack
    }

    interface OnCarIdBack {
        fun back(entity: CarLick)
    }


    private class EditAdapter :
        BaseQuickAdapter<CarLick, BaseViewHolder>(com.qc31.monitorlib.R.layout.item_search_edit) {
        override fun convert(holder: BaseViewHolder, item: CarLick) {
            holder.setText(com.qc31.monitorlib.R.id.tv_search_edit, sub("${item.carPlate}[${item.carName}]", 20))
        }
    }

}